/**
 * 
 */
package com.dengyuanke.spring.cloud.weather.service;

import java.io.IOException;
import java.util.Optional;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.dengyuanke.spring.cloud.weather.vo.WeatherResponse;

/**
 * 天气数据服务.
 * 
 * @since 1.0.0 2017年10月18日
 * @author <a href="https://waylau.com">Way Lau</a>
 */
@Service
public class WeatherDataServiceImpl implements WeatherDataService {

	private final static Logger LOGGER= LoggerFactory.getLogger(WeatherDataServiceImpl.class);

	@Autowired
	private RestTemplate restTemplate;
	@Autowired
	private StringRedisTemplate stringRedisTemplate;

	//换成超时时间
	private final Long TIME_OUT=1800L;


	private final String WEATHER_API = "http://wthrcdn.etouch.cn/weather_mini";



	@Override
	public WeatherResponse getDataByCityId(String cityId) {
		String uri = WEATHER_API + "?citykey=" + cityId;
		return this.doGetWeatherData(uri);
	}

	@Override
	public WeatherResponse getDataByCityName(String cityName) {
		String uri = WEATHER_API + "?city=" + cityName;
		return this.doGetWeatherData(uri);
	}

	@Override
	public void syncDataByCityId(String cityId) {
		String uri=WEATHER_API+"?citykey="+cityId;
		this.saveWeatherData(uri);
	}

	private void saveWeatherData(String uri) {
		ValueOperations<String,String> ops=this.stringRedisTemplate.opsForValue();
		String key=uri;
		String strBody=null;
		ResponseEntity<String> response = restTemplate.getForEntity(uri, String.class);
		if(response.getStatusCodeValue()==200){
			strBody=response.getBody();
		}
		ops.set(key,strBody,TIME_OUT,TimeUnit.SECONDS);

	}

	private WeatherResponse doGetWeatherData(String uri) {

		ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
		//将调用的URI作为缓存key
		String key=uri;

		String strBody = null;
		//先查询缓存，如果没有再查服务
		if(!this.stringRedisTemplate.hasKey(key)){
			LOGGER.info("未找到key"+key);
			ResponseEntity<String> response = restTemplate.getForEntity(uri, String.class);
			if (response.getStatusCodeValue() == 200) {
				strBody = response.getBody();
			}
			ops.set(key,strBody,TIME_OUT, TimeUnit.SECONDS);
		}else {
			LOGGER.info("找到 key"+key+",value="+ops.get(key));
			strBody=ops.get(key);
		}

		ObjectMapper mapper = new ObjectMapper();
		WeatherResponse weather = null;

		try {
			weather = mapper.readValue(strBody, WeatherResponse.class);
		} catch (IOException e) {
			LOGGER.error("JSON反序列化异常！",e);
			e.printStackTrace();
		}

		return weather;
	}

}